package string;

import org.junit.Test;

public class StringToIntegerAtoi8 {
    @Test
    public void test() {
        System.out.println(myAtoi("42"));
        System.out.println(myAtoi("-42"));
        System.out.println(myAtoi("4193 with words"));
        System.out.println(myAtoi("with words 987"));
        System.out.println(myAtoi("-91283472332"));
    }

    public int myAtoi(String s) {
        char[] c = s.toCharArray();
        int i = 0;
        while (i < c.length && c[i] == ' ') {
            i++;
        }
        if (i == c.length) {
            return 0;
        }

        boolean positive = true;
        if (c[i] == '+') {
            i++;
        } else if (c[i] == '-') {
            positive = false;
            i++;
        } else if (!Character.isDigit(c[i])){
            return 0;
        }

        long num = 0;
        while (i < s.length()) {
            if (!Character.isDigit(c[i])) {
                break;
            }
            int n = c[i] - '0';
            num = num * 10 + n;
            if (positive && num >= Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            if (!positive && num >= -(long)Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
            i++;
        }
        return positive ? (int)num : -(int)num;
    }
}
